<template>
  <el-dialog
    :visible.sync="visible"
    class="project-list-container"
    title="项目列表"
    width="60%"
    @close="dialogClose"
    @open="getProjectList"
    @opened="dialogOpened"
  >
    <el-form :model="requestParam" size="medium">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="选择单位" label-width="80px">
            <el-input v-if="JSON.stringify(companyCascaderArr) == '{}'" v-model="comName" disabled></el-input>
            <el-cascader
              :options="companyCascaderArr"
              v-else
              style="width:100%;"
              v-model="comp_ids"
              @change="onCompChange"
              :props="propParams"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="12" class="condition-style">
          <el-form-item>
            <div class="condition-input-style">
              <el-input
                @input="filterProjectListDebounce"
                placeholder="请输入项目代码/项目名称/项目地址查询"
                v-model="requestParam.search"
              ></el-input>
              <el-button
                type="primary"
                @click="onSearch"
                class="common-button-style"
                size="medium"
              >查询</el-button>
              <el-button class="common-button-style" @click="onReset" size="medium">重置</el-button>
            </div>

            <!-- <el-cascader placeholder="请选择收货地址"
                         @change="locationCascader"
                         v-model="requestParam.address"
                         class="choose-location-cascader"
                         :options="addressOptions">
            </el-cascader>-->
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="是否为已关联项目"
                        label-width="130px">
            <el-select v-model="requestParam.is_rela_project"
                       style="width:100%"
                       @change="onIsRelProject"
                       placeholder="请选择">
              <el-option v-for="item in isRelProArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>-->
        <!-- <el-col :span="6">
          <el-form-item prop="company_name">
            <el-select v-model="requestParam.company_name"> </el-select>
          </el-form-item>
        </el-col>-->

        <el-col :span="6" :offset="6">
          <!-- <el-form-item prop="project_name">
            <el-input placeholder="请输入项目名称" v-model="requestParam.project_name"> </el-input>
          </el-form-item>-->
        </el-col>
      </el-row>
    </el-form>
    <el-table
      :highlight-current-row="true"
      ref="menuTable"
      class="project-list-table"
      :data="projectList.list"
      :row-key="(row) => row.project_id"
      @selection-change="handleSelectionChange"
      @select="changeCheck"
      @select-all="changeAll"
      height="300"
      :header-cell-style="{ background: '#f5f5f5' }"
      border
    >
      <el-table-column type="selection" :reserve-selection="true" width="60"></el-table-column>
      <!-- <el-table-column width="60">
        <template slot-scope="scope">
          <el-checkbox @click.stop.prevent="(checked)=>{toggleProject(checked,scope.row)}"
                       v-model="scope.row.checked">
          </el-checkbox>
        </template>
      </el-table-column>-->
      <el-table-column
        label="项目代码"
        align="center"
        :show-overflow-tooltip="true"
        prop="project_code"
      ></el-table-column>
      <el-table-column
        label="项目名称"
        align="center"
        :show-overflow-tooltip="true"
        prop="project_name"
      ></el-table-column>
      <el-table-column label="项目地址" align="center" :show-overflow-tooltip="true" prop="address"></el-table-column>
      <!-- <el-table-column label="是否为关联项目"
                       align="center"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{scope.row.custom_project_type==2?'是':'否'}}</span>
        </template>
      </el-table-column>-->
      <el-table-column
        label="所属公司"
        align="center"
        :show-overflow-tooltip="true"
        prop="company_name"
      ></el-table-column>
    </el-table>
    <el-pagination
      id="pagination"
      background
      @current-change="handleCurrentChange"
      :current-page="requestParam.page"
      :page-size="requestParam.page_size"
      layout="total, prev, pager, next, jumper"
      :total="projectList.total_count"
    ></el-pagination>
    <div class="bottom-style">
      <el-button @click="dialogClose" size="medium">取消</el-button>
      <el-button type="primary" size="medium" @click="chooseProject">确定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { ProjectListApi } from "@/services/ProjectCenter";
import { projectDialogApi } from "@/services/ProjectCenter";
import { standardCodeApi } from "@/services/StandardCode";
import { _ } from "@/helper";
import { initGlobalState } from "qiankun";
export default {
  data() {
    return {
      isRelProArr: [
        { name: "是", value: 1 },
        { name: "否", value: 0 }
      ], //项目关联
      comp_ids: "",
      propParams: {
        multiple: true,
        checkStrictly: true,
        value: "org_no", //匹配响应数据中的id
        label: "name",
        children: "children_list"
      },
      companyCascaderArr: [], //级联
      comParam: {
        node_no: "",
        node_type: 1,
        show_dept: 0,
        show_job: 0,
        dept_type: ""
      },
      requestParam: {
        // is_rela_project: 0,//是否关联项目，1：是，0：否，要只显示关联项目，show_rela_project必须等于1
        show_rela_project: 0,
        org_no: [], //单位的主键值
        project_ids: "",
        // province_no: '',
        // city_no: '',
        // area_no: '',
        // company_id: '',
        project_name: "",
        search: "",
        page: 1,
        per_page: 10,
        module_id: "2",
        is_page: 1
      },
      filterParams: {
        search: "",
        org_no: ""
      },
      visible: false,
      projectList: {
        data: [],
        list: [],
        total: 0,
        total_count: 0
      },
      // 缓存项目列表，筛选时用
      tempProjectList: {
        data: [],
        list: [],
        total: 0,
        total_count: 0
      },
      // 专业类型列表
      majorTypeList: [],
      // // 专业类型map
      // majorTypeMap: new Map(),
      // 省市区列表
      addressOptions: [],
      // 已选择的项目数量
      projectNum: 0,
      // 已选择的项目列表
      choosedProjectList: [],
      indexProjectList: [],
      // 当前选中的项目
      choosedProject: {},
      checkIds: [], //选择的id
      totalArr: [], //回显加后来选择的id
      selArrs: [], //当前选中的信息
      defaultIds: [], //回显
      checkList: [],
      comName: ""
    };
  },
  methods: {
    onIsRelProject(val) {
      //是否是已关联项目show_rela_project
      let showRelPro = val == 1 ? 1 : val == 0 ? 0 : "";
      if (val == "") {
        showRelPro = "";
      }
      this.requestParam.show_rela_project = showRelPro;
      console.log("999999    val=", val, this.requestParam.show_rela_project);
    },
    getCurrentCompIds(newArr) {
      //当前已选中的单位
      let compIds = "";
      if (newArr.length > 0) {
        compIds = newArr.join(",");
      }
      this.requestParam.org_no = compIds; //单位的主键值
      this.filterProjectList(); //刷新
      // this.getProjectList() //根据选择的单位获取项目列表
    },
    //获取选择单位级联数据
    getComList() {
      projectDialogApi
        .getCompanyList({
          data: this.comParam
        })
        .then(
          res => {
            if (res.code === 0) {
              this.companyCascaderArr = res.data;
            }
          },
          err => {
            console.log(err);
          }
        );
    },
    //选择单位
    onCompChange(val) {
      //单位改变时触发的事件
      console.log(val);
      let arr = val;
      let newArr = [];
      if (arr.length > 0) {
        for (var item of arr) {
          item.map((item1, ind, arr) => {
            if (ind == item.length - 1) {
              newArr.push(item1);
            }
          });
        }
      }
      this.getCurrentCompIds(newArr); //获取选中的单位
      // console.log('单位主键值requestParam.comp_ids=', arr, newArr);
    },
    onSearch() {
      //查询
      // console.log(this.$store.state.choosedProjectList, '列表');
      this.getProjectList();
    },
    onReset() {
      //重置
      this.comp_ids = []; //单位的主键值
      // this.requestParam.is_rela_project = 0;
      this.requestParam.show_rela_project = 0;
      this.requestParam.project_ids = "";
      this.requestParam.org_no = "";
      this.requestParam.search = "";
      for (var i in this.filterParams) {
        this.filterParams[i] = "";
      }
      this.handleCurrentChange(1); //刷新
    },
    handleCurrentChange(val) {
      this.requestParam.page = val;
      this.getProjectList();
    },
    //项目列表参数
    getProject() {
      let conditions = [];

      for (var i in this.filterParams) {
        //为空不加入数组
        let obj = {};
        let item = this.filterParams[i];
        console.log(i, this.requestParam[i], "00");
        if (this.requestParam[i] !== "") {
          //输入框先写死
          if (i === "search") {
            obj = {
              column: "project_name",
              symbol: "like",
              value: this.requestParam[i]
            };
            conditions.push(obj);
          } else {
            if (this.requestParam[i] && this.requestParam[i].length > 0) {
              obj = {
                column: i,
                symbol: "=",
                value: this.requestParam[i]
              };
              conditions.push(obj);
            }
          }
        }
      }
      let params = {
        conditions: conditions,
        ...this.requestParam
      };
      return params;
    },
    // 获取项目列表
    getProjectList() {
      console.log(this.getProject(), "12345");
      ProjectListApi.getProjectManageList({
        // data: this.requestParam
        data: this.getProject()
      }).then(
        res => {
          if (res.code === 0) {
            this.projectList = res.data;
            // this.projectList.list.map((item, index) => {
            //   // item.majorTypeName = this.majorTypeMap.get(item.major_type).name
            //   // this.$set(item, 'checked', false)
            //   item.statusName = item.status === '1' ? '未完成' : '已完成'
            // })
            //是项目部的时候取列表的单位名称
            if (JSON.stringify(this.companyCascaderArr) == "{}") {
              this.comName = this.projectList.list[0].company_name;
            }
            this.tempProjectList = JSON.parse(JSON.stringify(this.projectList));
            this.getChecked(this.projectList.list || []);
          }
        },
        err => {
          console.log(err);
        }
      );
      this.getComList();
    },
    //页面回显
    getChecked(tableData) {
      console.log(this.selArrs);
      tableData.forEach(row => {
        this.$nextTick(() => {
          this.totalArr.forEach(item => {
            //表格默认选中,选中回显
            if (item === row.project_id) {
              this.$refs.menuTable.toggleRowSelection(row, true);
            }
          });
        });
      });
      return tableData;
    },
    //表格选择
    handleSelectionChange(data) {
      this.checkIds = [];
      this.checkList = [];
      data.forEach(item => {
        this.checkIds.push(item.project_id);
        this.checkIds = Array.from(new Set(this.checkIds));
        //去重
        this.checkList.push(item);
      });
      this.totalArr.push(...this.checkIds);
      this.totalArr = Array.from(new Set(this.totalArr));
      this.selArrs = this.filterArrObj(this.selArrs, this.checkList);
      if (data.length !== 0) {
        this.choosedProject = data[0];
      }
    },

    //点击取消选中
    changeCheck(selection, row) {
      let selected = selection.length && selection.indexOf(row) !== -1;
      //selected是当前点击的选中态
      if (selected === false || selected === 0) {
        this.$nextTick(() => {
          this.$refs.menuTable.selection.forEach(ele => {
            if (ele.project_id == row.project_id) {
              this.$refs.menuTable.toggleRowSelection(ele, false);
            }
          });
          let index = this.totalArr.indexOf(row.project_id);
          this.totalArr.splice(index, 1);
          this.selArrs.splice(index, 1);
        });
      }
    },
    //全选,选中子权限项
    changeAll(selection) {
      if (selection.length === 0) {
        this.$nextTick(() => {
          this.projectList.list.forEach(item => {
            let index = this.totalArr.indexOf(item.project_id);
            this.totalArr.splice(index, 1);
            this.selArrs.splice(index, 1);
          });
        });
      }
    },
    // 确定所选择的项目
    chooseProject() {
      if (Object.keys(this.choosedProject).length === 0) {
        this.$message.warning("请选择项目");
      } else {
        let state = {
          projectList: {
            list: []
          },
          choosedProject: {}
        };
        state.choosedProject = this.choosedProject;
        state.projectList.list = this.selArrs || [];
        const actions = initGlobalState(state);
        actions.setGlobalState(state);
        window.localStorage.setItem("totalArrs", JSON.stringify(this.totalArr));
        this.$store.dispatch("setProjectIdList", this.totalArr); //选择的id
        this.$store.dispatch("setProjectList", this.selArrs); //选择的信息
        this.$store.dispatch("setProject", this.choosedProject); //选中信息的第一个
        this.dialogClose();
      }
    },
    //合并去重,去掉重复的对象
    filterArrObj(json1, json2) {
      let json = json1.concat(json2); //两个数组对象合并
      let newJson = []; //盛放去重后数据的新数组
      for (let item1 of json) {
        //循环json数组对象的内容
        let flag = true; //建立标记，判断数据是否重复，true为不重复
        for (let item2 of newJson) {
          //循环新数组的内容
          if (item1.project_id == item2.project_id) {
            //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
            flag = false;
          }
        }
        if (flag) {
          //判断是否重复
          newJson.push(item1); //不重复的放入新数组。  新数组的内容会继续进行上边的循环。
        }
      }
      return newJson;
    },
    // 地址数据
    getAddressData() {
      fetch(`/static/area.json`, {
        method: "get",
        headers: {
          "Content-Type": "application/json"
        }
      })
        .then(res => {
          return res.json();
        })
        .then(res => {
          this.addressOptions = res.data;
        });
    },
    // 选择省市区
    locationCascader(item) {
      if (item.length === 3) {
        this.getProvinceByNo();
      }
    },

    // 根据no获取省数据
    getProvinceByNo() {
      this.addressOptions.map(item => {
        if (item.value === this.requestParam.address[0]) {
          this.requestParam.province = item.label;
          this.requestParam.province_no = item.value;
          this.getCityByNo(item.children);
        }
      });
    },
    // 根据no获取市数据
    getCityByNo(cityList) {
      cityList.map(item => {
        if (item.value === this.requestParam.address[1]) {
          this.requestParam.city = item.label;
          this.requestParam.city_no = item.value;
          this.getAreaByNo(item.children);
        }
      });
    },
    // 根据no获取区数据
    getAreaByNo(areaList) {
      areaList.map(item => {
        if (item.value === this.requestParam.address[2]) {
          this.requestParam.area = item.label;
          this.requestParam.area_no = item.value;
        }
      });
    },
    dialogClose() {
      this.$emit("update:dialogVisible", false);
    },
    // 弹框打开时，将已选中的项目的复选框置为选中状态
    dialogOpened() {
      // setTimeout(() => {
      //   this.projectList.list.map((item, index) => {
      //     // if (this.choosedProjectList.includes(item.project_id)) {
      //     if (this.choosedProjectList.project_id === item.project_id) {
      //       item.checked = true;
      //     }
      //   });
      // }, 0);
    },
    // 根据项目名称/项目地址筛选数据
    filterProjectList() {
      this.getProjectList();
    },
    // // 获取专业类型标准码
    // getMajorTypeCode () {
    //   standardCodeApi
    //     .getStandardCodeData({
    //       data: {
    //         code_type: 'major_type'
    //       }
    //     })
    //     .then(
    //       res => {
    //         if (res.code === 0 && res.data.list) {
    //           this.majorTypeList = res.data.list
    //           this.convertMajorListToMap(this.majorTypeList)
    //           window.localStorage.setItem(
    //             'platformMajorTypeList',
    //             JSON.stringify(this.majorTypeList)
    //           )
    //         }
    //       },
    //       err => {
    //         console.log(err)
    //       }
    //     )
    // },
    // // 将专业类型列表转换为map
    // convertMajorListToMap (list) {
    //   list.map(item => {
    //     this.majorTypeMap.set(item.value, item)
    //   })
    // },
    // 选择项目
    selectProject(selection) {
      this.projectNum = selection.length;
    },
    // 选择所有项目
    selectAll(selection) {
      this.projectNum = selection.length;
    }
  },
  props: {
    dialogVisible: Boolean
  },
  computed: {
    choosedProjectData() {
      let store = this.$store.state.choosedProject;
      let storage = window.localStorage.getItem("choosedProject");
      let data = store || storage;
      return data;
    }
  },
  watch: {
    dialogVisible(newval, oldval) {
      this.visible = newval;
      this.$nextTick(() => {
        this.$refs.menuTable.clearSelection();
        this.defaultIds = JSON.parse(window.localStorage.getItem("totalArrs"));
        this.checkIds = [];
        let newArr = [...this.defaultIds, ...this.checkIds]; //合并回显的选中id和后来新选中的
        newArr = Array.from(new Set(newArr));
        this.totalArr = newArr;
        this.getChecked(this.projectList.list);
      });
    },
    choosedProjectData: {
      handler(newval) {
        this.choosedProject = newval;
        this.projectList.list.map((item, index) => {
          if (this.choosedProject.project_id === item.project_id) {
            item.checked = true;
          }
        });
      },
      deep: true
    }
  },
  async created() {
    this.filterProjectListDebounce = _.debounce(() => {
      this.filterProjectList();
    }, 500);
  },
  async mounted() {
    // let majorTypeList = window.localStorage.getItem('platformMajorTypeList')
    // if (majorTypeList) {
    //   this.majorTypeList = JSON.parse(majorTypeList)
    //   this.convertMajorListToMap(this.majorTypeList)
    // } else {
    //   if (window.localStorage.getItem('access_token')) {
    //     await this.getMajorTypeCode()
    //   }
    // }
    setTimeout(() => {
      let local = JSON.parse(window.localStorage.getItem("choosedProject"));
      this.totalArr.push(local.project_id);
      window.localStorage.setItem("totalArrs", JSON.stringify(this.totalArr));
      this.selArrs.push(local);
      this.$store.dispatch("setProjectList", this.selArrs); //选择的信息
    }, 1000);
  },
  updated() {}
};
</script>
<style scoped lang="scss">
.condition-style {
  padding-left: 20px;
  margin-bottom: 20px;
  .condition-input-style {
    display: flex;
    flex-direction: row;
  }
  .common-button-style {
    margin-left: 14px;
  }
}
.bottom-style {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 20px;
}
</style>